﻿using Autofac;
using Crossroad.Core.Helper;
using Crossroad.System.Admin.Service;
using Crossroad.System.Admin.Service.Impl;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using Crossroad.Utils.Extensions;
using Crossroad.System.User.Model;
using System.Reflection;
using Crossroad.Core.Exceptions;
using SqlSugar;

namespace Crossroad.System.Admin.Attributes
{
    /// <summary>
    /// 权限特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class PermissionAttribute : Attribute, IActionFilter
    {
        private readonly RoleJoinMenuOptionService rmoService;

        public PermissionAttribute()
        {
            rmoService = AutofacOption.Container.Resolve<IRoleJoinMenuOptionService>() as RoleJoinMenuOptionService;
        }

        public PermissionAttribute(params string [] parameter)
        {
            rmoService = AutofacOption.Container.Resolve<IRoleJoinMenuOptionService>() as RoleJoinMenuOptionService;
            if(parameter.Length == 1 && parameter[0].IndexOf('@') < 0)
                Value = parameter[0];
            else
            {
                Values = new Dictionary<string, string>();
                foreach (var param in parameter)
                {
                    var props = param.Split('@');
                    Values[props[1]] = props[0];
                }
            }

        }

        /// <summary>
        /// 权限值
        /// </summary>
        public string Value { get; set; } = null;

        /// <summary>
        /// 权限值
        /// </summary>
        public Dictionary<string, string> Values { get; set; } = null;

        /// <summary>
        /// 操作列表
        /// </summary>
        public List<string> Options { get; set; } = null;

        /// <summary>
        /// Value值检查
        /// </summary>
        /// <param name="userApp"></param>
        private void ValueCheck(UserApp userApp)
        {
            if (Value.LastIndexOf('/') == Value.Length - 1)
            {
                Options = rmoService
                    .GetList(queryable =>
                        queryable.Where(a => a.roleId == userApp.roleId).Where(a => SqlFunc.Contains(a.value, Value)))
                    .Select(f => f.optionId).ToList();
            }
            else
            {
                var m = rmoService.GetEntity(queryable =>
                    queryable.Where(a => a.roleId == userApp.roleId && a.value.Equals(Value)));
                if (m.IsNull())
                    throw new LogicException("无操作权限！");
            }
        }

        /// <summary>
        /// 执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var userApp = context.Controller.GetNonPublicMemberValue("CurrentUserApp") as UserApp;
            var user = context.Controller.GetNonPublicMemberValue("CurrentUser") as UserInfo;
            //模糊匹配
            if (Values.NotNull())
            {
                var router = context.HttpContext.Request.Headers["Router"];
            
                if (!Values.ContainsKey(router))
                    return;

                Value = Values[router];
                ValueCheck(userApp);
            } else if (Value.NotNull())
            {
                ValueCheck(userApp);
            }

            if (!Options.IsNullOfEmpty())
                user.permissions = Options;
        }

        /// <summary>
        /// 执行后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
        }


    }
}